package dao

import (
	"github.com/jinzhu/gorm"
	"github.com/pkg/errors"
	"time"
)

type User struct {
	Id        int       `json:"id" gorm:"primary_key" description:"自增主键"`
	RoomId    int       `json:"room_id" gorm:"column:room_id" description:"房间ID"`
	Name      string    `json:"name" gorm:"column:name" description:"用户名称"`
	Token     string    `json:"token" gorm:"column:token" description:"用户token"`
	IsDelete  int       `json:"is_delete" gorm:"column:is_delete" description:"是否删除"`
	CreatedAt time.Time `json:"create_at" gorm:"column:create_at" description:"创建时间"`
}

type Result struct {
	RoomId    int
	UserCount int
}

func (u *User) TableName() string {
	return "chat_room_user"
}

/**
 * @Author: yang
 * @Description：获取用户列表
 * @Date: 2021/10/20 11:03
 */
func (u *User) List(tx *gorm.DB, in *User) ([]User, error) {
	var list []User
	// 数据查询
	if err := tx.Where("is_delete = 0 and room_id = ? ", in.RoomId).Find(&list).Error; err != nil {
		if nil == gorm.ErrRecordNotFound {
			return nil, errors.New("用户数据为空")
		}
		return nil, err
	}
	return list, nil
}

/**
 * @Author: yang
 * @Description：获取用户在线数量
 * @Date: 2021/10/26 16:51
 */
func (u *User) Count(tx *gorm.DB) (result []Result, err error) {
	err = tx.Table("chat_room_user").
		Select("room_id , count(*) as user_count").
		Group("room_id").
		Where("is_delete = 0").
		Scan(&result).Error
	return
}

/**
 * @Author: yang
 * @Description：添加聊天用户--保存
 * @Date: 2021/10/25 13:56
 */
func (u *User) Save(tx *gorm.DB) error {
	if err := tx.Save(u).Error; err != nil {
		return err
	}
	return nil
}

/**
 * @Author: yang
 * @Description：查找聊天用戶--查询
 * @Date: 2021/10/26 11:23
 */
func (u *User) Find(tx *gorm.DB, search *User) (*User, error) {
	out := &User{}
	if err := tx.Where(search).Find(&out).Error; err != nil {
		return nil, err
	}
	return out, nil
}
